﻿using Microsoft.AspNetCore.Mvc;

namespace Reporting.API.Controllers
{
    /// <summary>
    /// 上传文件控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadfileController : ControllerBase
    {

        private readonly QiniuUtils _qiniuUtils;

        public UploadfileController(QiniuUtils qiniuUtils)
        {
            _qiniuUtils = qiniuUtils;
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> UploadImages(IFormFile file)
        {
            // 检查文件是否为空
            if (file.Length == 0)
            {
                return BadRequest("文件为空");
            }

            // 生成文件名
            string name = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);

            // 使用 MemoryStream 读取文件数据
            using (var stream = new MemoryStream())
            {
                await file.CopyToAsync(stream);
                byte[] data = stream.ToArray();

                // 调用上传方法
                try
                {
                    _qiniuUtils.UploadFile(data, name);
                    string domain = "srgvmaq56.hd-bkt.clouddn.com";
                    string fileUrl = $"http://{domain}/images/{name}";

                    // 上传成功，返回文件的 URL
                    return Ok(new { Url = fileUrl });
                }
                catch (Exception ex)
                {
                    // 捕获上传异常并返回错误信息
                    return StatusCode(500, $"上传失败: {ex.Message}");
                }
            }
        }

    }
}
